package com.diytomcat.catalina;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.diytomcat.util.Constant;
import com.diytomcat.util.ServerXMLUtil;

/**
 * @author Leon Plious
 * @decription 主机
 */
public class Host {

	private String name;
	private Map<String, Context> contextMap;
	private Engine engine;
	
	public Host(String name, Engine engine) {
		this.contextMap = new HashMap<>();
		this.name = name;
		this.engine = engine;
		scanContextOnWebAppsFloder();
		scanContextInServerXML();
	}
	
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public Context getContext(String path) {
		return contextMap.get(path);
	}
	
	/**
	 * @description conf/server.xml文件读取webapps/root下的文件
	 * @2020年6月9日下午4:03:11
	 */
	private void scanContextInServerXML() {
		List<Context> contexts = ServerXMLUtil.getContext();
		
		for(Context context : contexts) {
			String path = context.getPath();
			contextMap.put(path, context);
		}
	}
	
	
	/**
	 * @description 非配置文件找webapps/root目录下的文件
	 * @2020年6月9日下午4:00:30
	 */
	private  void scanContextOnWebAppsFloder() {
		File[] floders = Constant.webappFolder.listFiles();
		
		for(File floder : floders) {
			if(!floder.isDirectory())
				continue;
			loadContext(floder);
		}
	}
	
	
	private void loadContext(File floder) {
		String path = floder.getName();
		if("ROOT".equals(path))
			path = "/";
		else
			path = "/" + path;
		
		String docBase = floder.getAbsolutePath();
		Context context = new Context(path, docBase);
		
		contextMap.put(context.getPath(), context);
	}
	
}
